package com.achievo.know.domain;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import com.achievo.know.core.KnowResourceBundleI18nService;
import com.dayatang.domain.BaseEntity;
import com.dayatang.domain.InstanceFactory;

/**
 * 角色
 * 
 * @author chencao
 * 
 */
@Entity
@Table(name = "RAMS_ROLE")
public class Role extends BaseEntity {
	
	public static final Long COMMONEMP=1L;
	public static final Long SUPERADMIN=2L;

	public enum Status {
		DISABLED, ENABLED
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -4179133191545832397L;

	// 角色名称
	@Column(name = "NAME", length = 50, nullable = false)
	private String name;

	// 状态
	@Column(name = "STATUS", nullable = false)
	private Status status;

	// 描述
	@Column(name = "DESCRIPTION", length = 1000)
	private String description;

	@ManyToMany(fetch=FetchType.LAZY)
	@JoinTable(name = "RAMS_ROLE_R_FUNCTION", joinColumns = { @JoinColumn(name = "ROLE_ID",insertable=false) }, inverseJoinColumns = { @JoinColumn(name = "FUNCTION_ID",insertable=true) })
	@OrderBy(value="id")
	private Set<Function> functions = new HashSet<Function>();
	
	@Column(name = "CAN_EDIT")
	private boolean canEdit;
	
	@ManyToMany(mappedBy = "roles",cascade=CascadeType.REFRESH)   
	private Set<User> users = new HashSet<User>();
	
	@ManyToMany
	@JoinTable(name="RAMS_ROLE_R_CATEGORY", joinColumns={@JoinColumn(name = "ROLE_ID") },inverseJoinColumns={@JoinColumn(name = "CATEGORY_ID")})
	@OrderBy(value="position")
	private Set<Category> categorys=new HashSet<Category>();
	
	public String getFuncStr(){
		StringBuilder b=new StringBuilder();
		List<Function> roots=getRoots();
		for(Function f:roots){
			b.append(f.getAlias());
			String childStr=getChildStr(f);
			if(StringUtils.isNotEmpty(childStr)){
				b.append("(").append(childStr).append(")");
			}
			b.append(",");
		}
		if(b.length()>0)
			b.deleteCharAt(b.length()-1);
		return b.toString();
	}
	
	private String getChildStr(Function parent){
		StringBuilder b=new StringBuilder();
		Iterator<Function> i= functions.iterator();
		while(i.hasNext()){
			Function t=i.next();
			if(t.getParent()!=null && parent.getId().longValue()==t.getParent().getId().longValue()){
				b.append(t.getAlias()).append(",");
			}
		}
		if(b.length()>0)
			b.deleteCharAt(b.length()-1);
		return b.toString();
	}
	
	private List<Function> getRoots(){
		List<Function> roots=new ArrayList<Function>();
		Iterator<Function> i= functions.iterator();
		while(i.hasNext()){
			Function t=i.next();
			if(t.getParent()==null){
				roots.add(t);
			}
		}
		return roots;
	}
	
	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	public boolean isCanEdit() {
		return canEdit;
	}

	public void setCanEdit(boolean canEdit) {
		this.canEdit = canEdit;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<Function> getFunctions() {
		return functions;
	}

	public void setFunctions(Set<Function> functions) {
		this.functions = functions;
		
	}

	public Set<Category> getCategorys() {
		return categorys;
	}

	public void setCategorys(Set<Category> categorys) {
		this.categorys = categorys;
	}

	@Override
	public boolean equals(Object obj) {
		
		 boolean flag = false; 
         if (obj != null && Role.class.isAssignableFrom(obj.getClass())) { 
        	    Role f = (Role) obj; 
                 flag = new EqualsBuilder() 
                                 .append(name, f.getName()) 
                                 .append(id, f.getId()) 
                                 .isEquals(); 
         } 
         return flag; 

	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public String toString() {
		return name;
	}
	
	
   /**
    * 仓储对象
    */
	private static RoleRepository roleRepository;

	public static RoleRepository roleRepository() {
		if (roleRepository == null) {
			roleRepository = InstanceFactory.getInstance(RoleRepository.class);
		}
		return roleRepository;
	}
	
	/**///////////////////////领域行为 start/////////////////////////////*/

	/**
	 * 创建
	 */
	public Role create(){
		
		boolean exists = getRoleByName(getName())!=null;
		
		if(exists){
			throw new RuntimeException(KnowResourceBundleI18nService.getMessage("auth.role.roleIsExist", "当前角色名称已经存在"));
		}
		this.setCanEdit(true);
		roleRepository().save(this);
		return this;
	}

	@SuppressWarnings("unchecked")
	public static Role getRoleByName(String name) {
        List<com.dayatang.domain.Entity> roles = roleRepository().find("from Role r where r.name=?", new Object[]{ name });
        return (Role) ((roles == null || roles.isEmpty())?null:roles.iterator().next());
    }
	
	/**
	 * 更新
	 */
	@SuppressWarnings("unchecked")
	public Role update(){
		
		 //原始对象
		Role originalRole = roleRepository().get(getId());
		
		//如果没做修改直接返回
		if(originalRole.equals(this)){
			if(StringUtils.equals(getDescription(), originalRole.getDescription()))
				return originalRole;
		}
		
     List<Role> exists = roleRepository().find("from Role r where r.name=? and r.id<>?", new Object[]{getName(),getId()});
		
		if(exists!=null && exists.isEmpty()==false){
			throw new RuntimeException(KnowResourceBundleI18nService.getMessage("auth.role.roleIsExist", "当前角色名称已经存在"));
		}
     
//		BeanUtils.copyProperties(t, originalRole);
		if(StringUtils.isNotEmpty(getName()))
			originalRole.setName(getName());
		if(StringUtils.isNotEmpty(getDescription()))
			originalRole.setDescription(getDescription());
		
		roleRepository().save(originalRole);
		return originalRole;
	}
	
	/**
	 * 删除
	 */
	public void delete(){
		
		List<User> accounts = User.getUserRepository().queryAccountByRole(this);
		if(accounts!=null){
			for (User account : accounts) {
				Set<Role> roles = account.getRoles();
				for (Role role : roles) {
					if(role.getId().equals(id)){
						roles.remove(role);
						account.setRoles(roles);
						User.getUserRepository().save(account);
						break;
					}
				}
			}
		}
		roleRepository().remove(this);
	}
	
	/**
	 * 状态注销
	 */
	public void disabled(){
		this.setStatus(Status.DISABLED);
		roleRepository().save(this);
	}
	
	/**
	 * 状态激活
	 */
	public void enabled(){
		this.setStatus(Status.ENABLED);
		roleRepository().save(this);
	}
	
	
	
	/**
	 * 授权
	 * @return
	 */
    public Role authorize(Set<Function> functions){
    	this.setFunctions(functions);
    	roleRepository().save(this);
    	return this;
    }
    
    public boolean isAdmin(){
    	if(StringUtils.isNotEmpty(this.name) && this.name.contains("管理员")){
    		return true;
    	}
    	return false;
    }
    
    public boolean isSuperAdmin(){
    	if(StringUtils.isNotEmpty(this.name) && this.name.contains("超级管理员")){
    		return true;
    	}
    	return false;
    }

}
